package com.dqy.twserver.server.handle.ehandle.mutil;

import com.dqy.twserver.server.dto.GameDto;
import com.dqy.twserver.server.handle.ehandle.GameEventHandle;
import com.dqy.twserver.server.support.Constans;
import com.dqy.twserver.server.support.MsgPush;
import com.dqy.twserver.server.support.Player;
import com.dqy.twserver.server.support.SupportMap;
import com.dqy.twserver.server.support.data.RoomInfo;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

public class GameEventInRoomHandle implements GameEventHandle ,IRoom{
    static Logger logger = LoggerFactory.getLogger(GameEventInRoomHandle.class);
    @Override
    public void handle(GameDto req, NioSocketChannel channel) throws Exception {
        logger.info("[GameEventInRoomHandle] start");

        GameDto resp=new GameDto();

        String playerName = req.getPlayerName();
        String roomId = req.getRoomId();
        int rid=roomIdToRid(roomId);
        logger.info("[GameEventReadiHandle] playerName={},roomId={},rid={}",playerName,roomId,rid);

        Map<Integer, RoomInfo> roomMap = SupportMap.roomMap;
        Map<String, Player> playerMap = SupportMap.playerMap;
        Player player = playerMap.get(playerName);
        RoomInfo roomInfo = roomMap.get(rid);
        if(roomInfo==null){
            logger.info("[GameEventReadiHandle] {}房间号不存在!",roomId);
            resp.setSts(400);
            resp.setInfo(roomId + "房间号不存在");
            channel.writeAndFlush(resp);
            return;
        }

        //判断是否已开始
        if("1".equals(roomInfo.getRoomSts())){
            logger.info("[GameEventReadiHandle] 游戏已开始");
            resp.setSts(400);
            resp.setInfo("该房间游戏已开始,不能进入");
            channel.writeAndFlush(resp);
            return;
        }

        List<Player> playerList = roomInfo.getPlayerList(); //获取当前房间的玩家
        if(playerList.size()>3){
            logger.info("[GameEventReadiHandle] {}房间人数以达到上限!",roomId);
            resp.setSts(400);
            resp.setInfo(roomId + "房间人数以达到上限（4人）");
            channel.writeAndFlush(resp);
            return;
        }

        playerList.add(player);
        player.setRoomId(rid);
        player.setPlayReadi(0);//默认不准备就绪
        resp.setSts(200);
        resp.setInfo(roomId+"加入成功!");

        String roomListInfoStr = getRoomInfo(playerList);
        logger.info("[GameEventReadiHandle] roomListInfoStr = {}",roomListInfoStr);
        logger.info("[GameEventReadiHandle] roomListInfoStr={}",roomListInfoStr);

        //給该房间内的所有人发一条通知
        String msgBody="[系统通知]：" +playerName +"进入房间";
        MsgPush.sendMsg(playerList,msgBody, "info",Constans.EVENT_TYPE_SEND_ALL_MSG); //向房间内所有人发送消息
        MsgPush.sendMsg(playerList,roomListInfoStr, "roomListStr",Constans.EVENT_TYPE_SEND_ROOM_INFO); //重新推送房间信息

        channel.writeAndFlush(resp);

        logger.info("[GameEventInRoomHandle] end");
    }
}
